package com.xsp.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xsp.eduservice.entity.EduCourse;
import com.xsp.eduservice.entity.EduCourseDescription;
import com.xsp.eduservice.entity.frontvo.CourseWebVo;
import com.xsp.eduservice.entity.vo.CourseInfoVo;
import com.xsp.eduservice.entity.vo.CoursePublishVo;
import com.xsp.eduservice.entity.vo.CourseQuery;
import com.xsp.eduservice.entity.frontvo.CourseFrontVo;
import com.xsp.eduservice.mapper.EduCourseMapper;
import com.xsp.eduservice.service.EduChapterService;
import com.xsp.eduservice.service.EduCourseDescriptionService;
import com.xsp.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xsp.eduservice.service.EduVideoService;
import com.xsp.commonutils.servicebase.exceptionhandler.GuLiException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-02-11
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    //后面对course_description表进行操作，因此需要提前注入该service
    EduCourseDescriptionService eduCourseDescriptionService;
    @Autowired
    EduChapterService eduChapterService;
    @Autowired
    EduVideoService eduVideoService;

    @Override
    //开启事务
    @Transactional
    //添加课程基本信息
    //添加完成后需要用到id，因此需要返回id值
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //创建EduCourse对象
        //将CourseInfoVo中对应的属性赋值给创建EduCourse对象,然后插入到course表中
        //由于这里本身就是course表的service实现类，因此直接使用baseMapper.insert，也可以使用this.save
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = baseMapper.insert(eduCourse);
        //插入失败则抛出异常
        if (insert == 0){
            throw new GuLiException(20001,"添加课程信息失败");
        }
        //保存course表的id，后续设置为course_description的id
        String pid = eduCourse.getId();
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        //将course表的id设置为course_description表的id
        eduCourseDescription.setId(pid);
        //将CourseInfoVo中的description属性赋值给course_description表的description
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        //将输入插入到course_description表中
        boolean save = eduCourseDescriptionService.save(eduCourseDescription);
        //保存失败则抛出异常
        if (!save){
            throw new GuLiException(20001,"添加课程信息失败");
        }
        return pid;
    }

    //根据课程id查询课程基本信息
    //由于基本信息包含了课程描述(简介),但它在另外的表,因此需要返回CourseInfoVo(包含课程简介)
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        //查询课程表
        EduCourse course = baseMapper.selectById(courseId);
        //查询课程描述(简介)表
        EduCourseDescription courseDescription = eduCourseDescriptionService.getById(courseId);
        //设置参数到courseInfoVo中
        BeanUtils.copyProperties(course,courseInfoVo);
        courseInfoVo.setDescription(courseDescription.getDescription());
        return courseInfoVo;
    }

    //修改课程信息
    @Override
//    @Transactional
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int i = baseMapper.updateById(eduCourse);
        if (i == 0){
            throw new GuLiException(20001,"修改课程信息出现异常...");
        }

        EduCourseDescription courseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVo,courseDescription);
        boolean b = eduCourseDescriptionService.updateById(courseDescription);
        if(!b){
            throw new GuLiException(20001,"修改课程信息出现异常...");
        }

    }

    //确认发布的信息
    @Override
    public CoursePublishVo getCoursePublishVo(String id) {
        return baseMapper.getCoursePublishVo(id);
    }

    //删除课程信息(小节,章节,描述,课程)
    @Override
    public void deleteCourse(String courseId) {
        //课程id删除小节
        eduVideoService.removeByCourseId(courseId);
        //课程id删除章节
        eduChapterService.removeByCourseId(courseId);
        //课程id删除描述
        eduCourseDescriptionService.removeById(courseId);
        //课程id删除课程
        int i = baseMapper.deleteById(courseId);
        if (i == 0){
            throw new GuLiException(2001,"课程删除失败！");
        }
    }

    //条件查询和分页
    @Override
    public Page<EduCourse> pageCourseCondition(long page, long limit, CourseQuery courseQuery) {
        //创建分页对象
        Page<EduCourse> coursePage = new Page<>(page,limit);
        //创建Wrapper条件对象
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        //保存CourseQuery对象各个属性的值
        String title = courseQuery.getTitle();
        String status = courseQuery.getStatus();
        String begin = courseQuery.getBegin();
        String end = courseQuery.getEnd();

        //对传入的CourseQuery各个属性值进行判断，如果不是空则进入wrapper添加条件
        if (!StringUtils.isEmpty(title)){
            queryWrapper.like("title",title);
        }

        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("status",status);
        }

        if (!StringUtils.isEmpty(begin)){
            queryWrapper.ge("gmt_create",begin);
        }

        if (!StringUtils.isEmpty(end)){
            queryWrapper.le("gmt_modified",end);
        }
        //根据创建时间降序排列
        queryWrapper.orderByDesc("gmt_create");
        //将分页对象和条件对象传入
        baseMapper.selectPage(coursePage,queryWrapper);
        return coursePage;
    }

    //讲师id获取课程信息
    @Override
    public List<EduCourse> selectByTeacherId(String id) {
        QueryWrapper<EduCourse> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("teacher_id",id);
        List<EduCourse> courseList = baseMapper.selectList(queryWrapper);
        return courseList;
    }

    //前台课程分页条件查询
    @Override
    public Map<String, Object> getFrontCourseList(Page<EduCourse> coursePage, CourseFrontVo courseFrontVo) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        //如果传入的Vo有值，则进入后续的判断
        if (!StringUtils.isEmpty(courseFrontVo)){
            //一级分类
            if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())){
                queryWrapper.eq("subject_parent_id", courseFrontVo.getSubjectParentId());
            }
            //二级分类
            if (!StringUtils.isEmpty(courseFrontVo.getSubjectId())){
                queryWrapper.eq("subject_id", courseFrontVo.getSubjectId());
            }
            //购买量降序
            if (!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())){
                queryWrapper.orderByDesc("buy_count");
            }
            //课程创建时间降序
            if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())){
                queryWrapper.orderByDesc("gmt_create");
            }
            //价格升降序
            if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())){
                //如果传入的值是1则降序
                if (courseFrontVo.getPriceSort().equals("1")){
                    queryWrapper.orderByDesc("price");
                //如果传入的值是2则升序
                }else if (courseFrontVo.getPriceSort().equals("2")){
                    queryWrapper.orderByAsc("price");
                }

            }
        }

        //会把分页对象封装到coursePage中
        baseMapper.selectPage(coursePage,queryWrapper);
        //拿到分页对象的数据
        List<EduCourse> records = coursePage.getRecords();
        long current = coursePage.getCurrent();
        long pages = coursePage.getPages();
        long size = coursePage.getSize();
        long total = coursePage.getTotal();
        boolean hasNext = coursePage.hasNext();
        boolean hasPrevious = coursePage.hasPrevious();
        //放入分页对象的数据
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        //返回分页对象的数据
        return map;
    }

    @Override
    public CourseWebVo getFrontCourseInfo(String courseId) {
        return baseMapper.getFrontCourseInfo(courseId);
    }
}
